package gzdev;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 生成实体类代码
 */
public class GenerateEntity extends GzFile {

    // 实体类的名称模板
    private final String entityName;

    // 实体类包名
    private final String packageName;

    private final GzConfig config;

    public GenerateEntity(GzConfig config) {
        super();
        entityName = "%s";
        this.packageName = config.getPojoPackage();
        this.config = config;
    }

    /**
     * 输出实体类到指定位置
     *
     * @param tableName      数据库表名
     * @param tableStructure 数据库表结构
     */
    public void outEntity(String tableName, List<Map<String, Object>> tableStructure) throws IOException {
        StringBuilder content = new StringBuilder();
        appendHeader(content, tableName);
        appendBody(content, tableName, tableStructure);
        appendFooter(content);
        out(packageName, String.format(entityName, getJavaNameFromTb(tableName)) + ".java", content.toString());
    }

    /**
     * 添加头部的代码
     *
     * @param tableName
     */
    private void appendHeader(StringBuilder stringBuilder, String tableName) {
        String template = "package %s;\n\npublic class %s {";
        String pojoName = String.format(entityName, getJavaNameFromTb(tableName));
        stringBuilder.append(String.format(template, packageName, pojoName));
    }

    private void appendFooter(StringBuilder stringBuilder) {
        stringBuilder.append("\n}");
    }

    /**
     * 填充实体类中间的代码
     *
     * @param stringBuilder
     * @param tableStructure 数据库表结构
     */
    private void appendBody(StringBuilder stringBuilder, String tableName, List<Map<String, Object>> tableStructure) {
        String valTemplate = "\n\n\tprivate %s %s;";
        String getTemplate = "\n\n\tpublic %s get%s() {\n\t\treturn %s;\n\t}";
        String setTemplate = "\n\n\tpublic %s set%s(%s %s) {\n\t\tthis.%s = %s;\n\t\treturn this;\n\t}";
        // val
        for (Map<String, Object> map : tableStructure) {
            String name = getValNameFromColumn((String) map.get(GzDBInfo.COLUMN_NAME));
            String type = config.getJavaType((String) map.get(GzDBInfo.TYPE));
            stringBuilder.append(String.format(valTemplate, type, name));
        }
        // getter and setter
        for (Map<String, Object> map : tableStructure){
            String pojoName = String.format(entityName, getJavaNameFromTb(tableName));
            String name = getValNameFromColumn((String) map.get(GzDBInfo.COLUMN_NAME));
            String nameOfMethod = getJavaNameFromTb((String) map.get(GzDBInfo.COLUMN_NAME));
            String type = config.getJavaType((String) map.get(GzDBInfo.TYPE));
            stringBuilder.append(String.format(getTemplate, type, nameOfMethod, name));
            stringBuilder.append(String.format(setTemplate,pojoName, nameOfMethod, type, name, name, name));
        }
    }


}
